import React, { PureComponent } from 'react';
import '@ant-design/compatible/assets/index.css';
import { Badge, Card, message, Table, Row, Col, Button, Popconfirm } from 'antd';
import { connect } from 'dva';
import PateoTable from '../../../components/common/PateoTable';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import styles from '../../../components/common/PateoTable/TableList.less';
import Ellipsis from '../../../components/Ellipsis';
import LogModal from './logModal';
import LockModal from './lockModal';
import AlarmModal from './alarmModal';
import TaskModal from '../taskCenter';

const mapStateToProps = (state:any) => ({
  commercialVehicle: state.commercialVehicle,
  loading: state.loading.models["commercialVehicle"],
  user: state?.menu?.userProfile
});
class CommercialVehicle extends PureComponent<any, any> {

  constructor(props: any) {
    super(props);
    this.state = {
      currentVehicleVin: '', 
      logVisible: false,
      lockVisible: false,
      alarmVisible: false,
      taskCenterVisible: false,
      brandList: [],  //  品牌
      seriesList: [], //  车系
      vehicleTypeList: [], // 车型
      // vehicleType
      activeTypeList: [{
        value: 1, label: '用户车',
      }, {
        value: 2, label: '试乘试驾车'
      }, {
        value: 3, label: '展车'
      }, {
        value: 4, label: '内部测试车'
      }, {
        value: 5, label: '媒体车'
      }, {
        value: 6, label: '质检车'
      }],
      formValues: {
        // lockStatus: '0',
        // warnStatus: '0',
      },
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const tempParam = {
      ...formValues,
      pageNo: 1,
      pageSize: 10
    }
    dispatch({
      type: 'commercialVehicle/postFetchPageParamAndBody',
      payload: { url: '/commodity/vehicle/monitor/info/page', ...tempParam },
    });
    this.getBrandData()
  }

  //  获取品牌数据列表
  getBrandData = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'commercialVehicle/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          this.setState({
            brandList: res.data.map((item: any) => ({
              label: item.brandName,
              value: item.brandCode
            })),
            seriesList: [],
            vehicleTypeList: [],
          })
        }
      }
    })
  }

  //  获取车系数据列表
  getSeriesData = (t: any) => {
    const { dispatch } = this.props;
    const brandId = this.searchForm.current.getFieldValue('brandCode')
    //  重置车系、车型
    /* this.searchForm.current.setFieldsValue({
      vehicleSeries: undefined,
      vehicleType: undefined,
    }) */
    this.searchForm.current.resetFields(['vehicleSeries', 'vehicleType']);
    this.setState({
      seriesList: [],
      vehicleTypeList: []
    })
    brandId && dispatch({
      type: 'vehicleInfoQuery/getDataWithRes',
      payload: {
        url: '/common/vehicle/getserieslist',
        brandId,
      },
      callback: (res: any) => {
        this.setState({
          seriesList: res.data.map((item: any) => ({
            label: item.name,
            value: item.code,
          })),
        });
      },
    })
  }

  //  获取车型数据列表
  getVehicleTypeData = (t: any) => {
    const { dispatch } = this.props;
    const tempVehicleSeries = this.searchForm.current.getFieldValue('vehicleSeries')
    /* this.searchForm.current.setFieldsValue({
      vehicleType: undefined,
    }) */
    this.setState({ vehicleTypeList: [] });
    this.searchForm.current.resetFields(['vehicleType']);
    const brandId = this.searchForm.current.getFieldValue('brandCode');
    const seriesId = this.searchForm.current.getFieldValue('vehicleSeries');
    //  重置车型
    brandId && seriesId && 
      dispatch({
        type: 'vehicleInfoQuery/getDataWithRes',
        payload: {
          url: '/common/vehicle/gettypelist',
          brandId,
          seriesId,
        },
        callback: (res: any) => {
          this.setState({
            vehicleTypeList: res.data.map((item: any) => ({
              label: item.name,
              value: item.code,
            })),
          });
        }
      })
    /* if (tempVehicleSeries) {
      setTimeout(() => {
        this.setState({
          vehicleTypeList: [
            {
              value: '0',
              label: '车型一'
            },
            {
              value: '1',
              label: '车型二'
            }
          ]
        })
      }, 300)
    } else {
      this.setState({
        vehicleTypeList: []
      })
    } */
  }

  //  请求回调处理数据
  /* dispatch({
    type: 'consumerLog/postDataWithResNoPut',
    payload: { url: '/newFeedback/saveDownloadRecord', ...params },
    callback: (res: any) => {
      dispatch({
        type: 'consumerLog/postFetchPage',
        payload: { url: '/newFeedback/findPageList', ...tempParam },
      });
    }
  }); */

  handleFormReset = () => {
    this.setState({
      formValues: {
        // lockStatus: '0',
        // warnStatus: '0',
      },
      seriesList: [],
      vehicleTypeList: [],
    });
  }

  //  锁车
  handleLock = (record: any) => {
    this.setState({
      currentVehicleVin: record?.vin,
      lockVisible: true
    })
  }

  //  解锁
  handleUnlock = (record: any) => {
    const { dispatch, user } = this.props;
    dispatch({
      type: 'commercialVehicle/postDataWithRes',
      payload: {
        url: `/commodity/vehicle/monitor/unlock/${record?.vin}`,
        operator: user?.accountName,
      },
      callback: (res: any) => {
        this.handleFresh()
      }
    })
  }

  //  车机告警
  handleAlarm = (record: any) => {
    this.setState({
      currentVehicleVin: record?.vin,
      alarmVisible: true
    })
  }

  //  解除车机告警
  handleClearAlarm = (record: any) => {
    const { dispatch, user } = this.props;
    dispatch({
      type: 'commercialVehicle/postDataWithRes',
      payload: {
        url: `/commodity/vehicle/monitor/unWarn/${record?.vin}`,
        operator: user?.accountName,
      },
      callback: (res: any) => {
        this.handleFresh()
      }
    })
  }

  handleLogShow = (record: any) => {
    this.setState({
      currentVehicleVin: record?.vin,
      logVisible: true
    })
  }

  handleTaskCenterModalShow = () => {
    this.setState({
      taskCenterVisible: true
    })
  }

  closeLogModal = () => {
    this.setState({
      logVisible: false,
      currentVehicleVin: ''
    });
  }

  closeLockModal = () => {
    this.setState({
      lockVisible: false,
      currentVehicleVin: ''
    });
  }

  closeAlarmModal = () => {
    this.setState({
      alarmVisible: false,
      currentVehicleVin: ''
    });
  }

  closeTaskCenterModal = () => {
    this.setState({
      taskCenterVisible: false,
    });
  }

  //  更新数据
  handleFresh = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const tempParam = {
      ...formValues,
      pageNo: 1,
      pageSize: 10
    }
    dispatch({
      type: 'commercialVehicle/postFetchPageParamAndBody',
      payload: { url: '/commodity/vehicle/monitor/info/page', ...tempParam },
    });
  }

  render() {
    const { commercialVehicle: { pageData: { rows, pagination, total }, }, loading, dispatch, location: { pathname = '/' } } = this.props;
    // let pathname = '/commercialVehicleMonitor/commercialVehicle'
    // const { formValues, selectedRowKeys, detailVisible } = this.state;
    const { formValues, brandList, seriesList, vehicleTypeList, activeTypeList, logVisible, lockVisible, alarmVisible, taskCenterVisible, currentVehicleVin } = this.state;

    const columns = [
      /* {
        title: '序号',
        dataIndex: 'no',
        width: 60,
        render: (text:any, record:any, index:any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      }, */
      {
        title: 'VIN',
        dataIndex: 'vin',
      },
      {
        title: '品牌',
        dataIndex: 'brandCode',
      },
      {
        title: '车系',
        dataIndex: 'vehicleSeries',
      },
      {
        title: '车型',
        dataIndex: 'vehicleType',
      },
      {
        title: '车辆激活类型',
        dataIndex: 'vhlType',
        render: (text: any) => {
          let tempStr = ''
          activeTypeList.some((v: any) => {
            const state = v.value == text
            if (state) {
              tempStr = v.label
            }
            return state
          })
          return tempStr
        }
      },
      {
        title: '风控状态',
        dataIndex: 'lockStatus',
        render: (text: any) => text == 0 ? '正常' : '已锁车'
      },
      {
        title: '风控实车状态',
        dataIndex: 'vehLockStatus',
        render: (text: any) => text == 0 ? '正常' : '已锁车'
      },
      {
        title: '车机告警状态',
        dataIndex: 'warnStatus',
        render: (text: any) => text == 0 ? '正常' : '车机告警'
      },
      // {
      //   title: '用户名',
      //   dataIndex: 'id',
      //   render: (text:any) => {
      //     return (
      //       <Ellipsis length={10} tooltip>
      //         {text}
      //       </Ellipsis>
      //     );
      //   },
      // },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 240,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '锁车',
              key: 'lock',
              auth: 'vehicle_doLock',
              // message: '确认锁车？',
              // Popconfirm: true,
              hide: record.lockStatus !== 0,  //  风控状态
              onConfirm: () => { this.handleLock(record) },
            },
            {
              title: '解除锁车',
              key: 'unlock',
              auth: 'vehicle_doUnLock',
              message: '确认解除锁车，同时解除车机告警？',
              Popconfirm: true,
              hide: record.lockStatus !== 1,
              onConfirm: () => { this.handleUnlock(record) },
            },
            {
              title: '车机告警',
              key: 'alarm',
              auth: 'vehicleSys_doAlarm',
              hide: record.warnStatus !== 0,
              onConfirm: () => { this.handleAlarm(record) },
            },
            {
              title: '解除车机告警',
              key: 'clearAlarm',
              auth: 'vehicleSys_doClearAlarm',
              message: record.lockStatus === 1 ? '确认解除车机告警，同时解除锁车？' : '确认解除车机告警？',
              Popconfirm: true,
              hide: record.warnStatus !== 1,
              onConfirm: () => { this.handleClearAlarm(record) },
            },
            {
              title: '操作记录',
              key: 'log',
              auth: 'operationLog_show',
              onConfirm: () => { this.handleLogShow(record) },
            }
          ]
          return <PateoAuthButtons btns={btns} max={3} pathname={pathname} />;
        }
      },
    ]

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      total,
      showTotal: () => (
        <span>共&nbsp;{total}&nbsp;条</span>
      ),
    };
    // const rowSelection = {
    //   selectedRowKeys,
    //   onChange: (selectedRowKeys: any) => { this.setState({ selectedRowKeys })},
    // };
    const tableProps = {
      columns,
      rowKey: (record: any) => record.vin, //  record.id
      dataSource: rows,
      loading,
      pagination: paginationProps,
      // rowSelection,
      // selectedRowKeys,
      scroll: { x: 'max-content' }
    }

    const searchItems = [
      {
        title: 'VIN',
        type: 'input',
        // customStyle: 6,
        key: 'vin',
      },
      {
        title: '品牌',
        type: 'select',
        selectOptions: brandList,
        onChange: (e: any) => {
          this.getSeriesData(e)
        },
        keyValue: ['value', 'label'],
        key: 'brandCode',
      },
      {
        title: '车系',
        type: 'select',
        selectOptions: seriesList,
        // keyValue: ['seriesCode', 'seriesName'],
        onChange: (e: any) => {
          this.getVehicleTypeData(e)
        },
        key: 'vehicleSeries',
      },
      {
        title: '车型',
        type: 'select',
        selectOptions: vehicleTypeList,
        key: 'vehicleType',
      },
      {
        title: '车辆激活类型',
        type: 'select',
        selectOptions: activeTypeList,
        key: 'vhlType',
      },
      {
        title: '风控状态',
        type: 'select',
        // initialValue: '0',
        selectOptions: [
          { value: '0', label: '正常' },
          { value: '1', label: '已锁车' },
        ],
        key: 'lockStatus',
      },
      {
        title: '风控实车状态',
        type: 'select',
        // initialValue: '0',
        selectOptions: [
          { value: '0', label: '正常' },
          { value: '1', label: '已锁车' },
        ],
        key: 'vehLockStatus',
      },
      {
        title: '车机告警状态',
        type: 'select',
        // initialValue: '0',
        selectOptions: [
          { value: '0', label: '正常' },
          { value: '1', label: '车机告警' },
        ],
        key: 'warnStatus',
      },
    ]

    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => this.searchForm = val}
            searchItems={searchItems}
            fetchParams={{ type: 'commercialVehicle/postFetchPageParamAndBody', url: '/commodity/vehicle/monitor/info/page' }}
            extraArgs={{pageNo:1, pageSize:10}}
            saveFormValues={(val:any) =>
              this.setState({
                formValues: Object.assign(formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
            // handleFieldsValue={this.dataFormat}
          />
        </Card>

        <Card className={styles.standardTable}>
          <div>
            <Row>
              <Col span={12}>
                <Button
                  style={{ marginBottom: 8, marginRight: 8 }}
                  type={"primary"}
                  onClick={() => { this.handleTaskCenterModalShow() }}
                >
                  任务中心
                </Button>
              </Col>
              <Col span={12}></Col>
            </Row>
          </div>
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'commercialVehicle/postFetchPageParamAndBody', url: '/commodity/vehicle/monitor/info/page', extraArgs: {} }}
            formValues={formValues}
            currentName="pageNo"
            pageSizeName="pageSize"
          />
        </Card>
        <LogModal 
          onRef={(val: any) => (this.logModal = val)}
          vehicleVin={currentVehicleVin}
          modalVisible={logVisible}
          closeModal={this.closeLogModal}
        />
        <LockModal
          onRef={(val: any) => (this.lockModal = val)}
          vehicleId={currentVehicleVin}
          modalVisible={lockVisible}
          refreshPage={this.handleFresh}
          closeModal={this.closeLockModal}
        />
        <AlarmModal 
          onRef={(val: any) => (this.alarmModal = val)}
          vehicleId={currentVehicleVin}
          modalVisible={alarmVisible}
          refreshPage={this.handleFresh}
          closeModal={this.closeAlarmModal}
        />
        <TaskModal 
          onRef={(val: any) => (this.taskCenterModal = val)}
          modalVisible={taskCenterVisible}
          closeModal={this.closeTaskCenterModal}
        />

      </div>
    )
  }
}
export default connect(mapStateToProps)(CommercialVehicle);
